import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { getArtistList } from '../service/artist'
import type { ArtistType } from '../store/type'

export const fetchArtistListAction = createAsyncThunk(
  'artistCategory',
  async (
    payload: { area: number; type: number; initial: string },
    { dispatch }
  ) => {
    const { area, type, initial } = payload
    getArtistList(area, type, initial).then((res) => {
      console.log(res.artists, 'artistList')
      dispatch(changeArtistListAction(res.artists))
    })
  }
)

export interface ArtistState {
  artistList: ArtistType[]
  currentArea: number
  currentType: { name: string; type: number }
}

const initialState: ArtistState = {
  artistList: [],
  currentArea: 7,
  currentType: {
    name: '推荐歌手',
    type: 1
  }
}

export const artistSlice = createSlice({
  name: 'artist',
  initialState,
  reducers: {
    changeArtistListAction: (state, { payload }) => {
      state.artistList = payload
    },
    changeCurrentAreaAction: (state, { payload }) => {
      state.currentArea = payload
    },
    changeCurrentTypeAction: (state, { payload }: { payload: { type: number; name: string } }) => {
      state.currentType.name = payload.name
      state.currentType.type = payload.type
    }
  }
})

export default artistSlice.reducer
export const {
  changeArtistListAction,
  changeCurrentAreaAction,
  changeCurrentTypeAction
} = artistSlice.actions
